package com.mall.order.controller;

import com.ctg.mse.common.exception.BizException;
import com.ctg.mse.common.model.error.CommonCode;
import com.ctg.mse.common.model.result.ResultGeneralModel;
import com.mall.order.api.OrderApi;
import com.mall.order.dao.entity.TOrder;
import com.mall.order.model.OrderInfo;
import com.mall.order.service.OrderService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: OrderApi的实现类
 * @Author: zhouzh
 * @CreateTime: 2022-10-21  22:43
 */
@RestController
public class OrderApiImpl implements OrderApi {

    private final static Logger LOGGER = LoggerFactory.getLogger(OrderApiImpl.class);

    @Autowired
    private OrderService orderService;

    @Override
    public ResultGeneralModel<OrderInfo> modifyOrderState(Long orderId, Integer state) {
        TOrder tOrder;
        try{
            tOrder = orderService.modifyState(orderId, state);
            if(tOrder == null){
                return ResultGeneralModel.newFail(CommonCode.DATA_NOT_EXIST,"orderId is not exist");
            }
        }catch(Exception e){
            LOGGER.error("",e);
            throw e;
        }

        return ResultGeneralModel.newSuccess(tOrder);
    }

    @Override
    public ResultGeneralModel<List<Long>> getProductsSales(String productIds) {

        List<Long> productsSales;
        try{
            productsSales = orderService.getProductsSales(parseToIdList(productIds));
        }catch(Exception e){
            LOGGER.error("",e);
            throw e;
        }

        //每次下单redis中相关产品销量就+1，查redis
        return ResultGeneralModel.newSuccess(productsSales);
    }

    private List<Long> parseToIdList(String ids){

        String[] idList = ids.split(",");
        List<Long> idLongList = new ArrayList<>();
        for (String id : idList) {
            if(!StringUtils.isNumeric(id) || StringUtils.isBlank(id)){
                throw new BizException(CommonCode.ILLEGAL_PARAM);
            }
            idLongList.add(Long.parseLong(id));
        }

        return idLongList;
    }


}
